package jlu.com.p2pclient.service;

import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.jlu.mcloud.communicate.heartbeat.Command;
import com.jlu.mcloud.communicate.heartbeat.HeartbeatClient;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import jlu.com.p2pclient.utils.Config;
import jlu.com.p2pclient.utils.HeartBeatListerner;

/**
 * @Author freedom
 * @DATE 2017/5/19 0019 16:50.
 * see   心跳包服务
 */

public class HeartBeatService extends Service {
    public static final String TAG = "HeartbeatService";
    private HeartbeatBinder binder = new HeartbeatBinder();
    private ActivityManager activityManager;
    private Context context;
    private String serverResult;
    private HeartBeatListerner listerner;

    HeartbeatClient heartbeatClient = new HeartbeatClient() {

        @Override
        protected boolean processCommand(Command command) {
            serverResult = command.getInfo().get("ack").toString();
            /*接口回调更新ui*/
            if (listerner != null) {
                listerner.isConnected(serverResult);
            }
            return true;
        }

        /*获取手机序列号*/
        @Override
        protected String getNodeId() {
            return Config.DEVICE_ID;
        }

        /*获取手机相关参数*/
        @Override
        protected Map<String, Object> getInfo() {
            Map<String, Object> info = new HashMap<String, Object>();
            ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
            activityManager.getMemoryInfo(memoryInfo);
            info.put(Config.TAG_TOTAL_MEMORY, memoryInfo.totalMem);
            info.put(Config.TAG_AVAIL_MEMORY, memoryInfo.availMem);
            info.put(Config.TAG_THRESHOLD, memoryInfo.threshold);
            info.put(Config.TAG_IS_LOWMEMORY, memoryInfo.lowMemory);
            info.put(Config.TAG_LEFT_POWER, getBatteryLeft());
            info.put(Config.TAG_CPU_FREQUENCY, getMaxCpuFreq());
            info.put(Config.NODE_IP, Config.getHostIp());
            return info;

        }


    };

    /*获取回调接口实例*/
    public void setHeartBeatListener(HeartBeatListerner listener){
        this.listerner = listener;
    }


    /**
     * see   获取手机最大CPU频率
     *
     * @入参 void
     * @出参 String 获取手机最大CPU频率
     */
    private String getMaxCpuFreq() {
        String result = "";
        ProcessBuilder cmd;
        try {
            String[] args = {"/system/bin/cat", "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"};
            cmd = new ProcessBuilder(args);
            Process process = cmd.start();
            InputStream in = process.getInputStream();
            byte[] re = new byte[24];
            while (in.read(re) != -1) {
                result = result + new String(re);
            }
            in.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            result = "N/A";
        }
        return result.trim();
    }

    /**
     * see   获取手机当前电量
     *
     * @入参 void
     * @出参 String 当前电量
     */
    private String getBatteryLeft() {
        String result = "0";
        IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = getApplication().registerReceiver(null, ifilter);
        int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        result = String.valueOf(level);
        if (result.equals("0")) {
            return "1";
        }
        return result;

    }

    @Override
    public void onCreate() {
        super.onCreate();
        heartbeatClient.setInetAddress(Config.SERVER_IP, Config.SERVER_PORT);
        new Thread(heartbeatClient).start();
        Log.w(TAG, "onCreate: HeartbeatService");
        activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        context = this.getApplicationContext();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.w(TAG, "onDestroy: HeartbeatService");
        heartbeatClient.stop();
        serverResult="wrong";
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }


    /*获取当前服务对象以调用listener*/
    public class HeartbeatBinder extends Binder {

       public HeartBeatService getService(){
           return HeartBeatService.this;
       }
    }
}
